package com.cictec.middleware.ribbon.aspect;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 线程处理存储对象
 * 
 * @author Administrator
 *
 */
public class ThreadContextHolder {

	/** 线程内共享，ThreadLocal通常是全局的，支持泛型 */
	
	private static final ThreadLocal<LinkedList<ConcurrentHashMap<String, String>>> dataHolder = new ThreadLocal<LinkedList<ConcurrentHashMap<String, String>>>() {
		@Override
		protected LinkedList<ConcurrentHashMap<String, String>> initialValue() {
			return new LinkedList<ConcurrentHashMap<String, String>>();
		}

	};
//	private static ThreadLocal<Map<String, String>> threadLocal = new ThreadLocal<Map<String, String>>();
//	public static ThreadLocal<String> valueCityCode = new ThreadLocal<String>() {
//
//		@Override
//		public String initialValue() {
//			return new String();
//		}
//
//	};
	/**
	 * 设备在当前线程缓存信息(城市编码)
	 * @param devCode
	 * @param cityCode
	 */
	public static void setValue(String devCode, String cityCode) {
		LinkedList<ConcurrentHashMap<String, String>> list = dataHolder.get();
		if(list.size() == 0){
			ConcurrentHashMap<String, String> _map = new ConcurrentHashMap<String, String>();
			_map.put(devCode, cityCode);
			_map.put("devCode", devCode);
			_map.put("cityCode", cityCode);
			list.add(_map);
			// 并且设置当前数据为第一个
			determineCurrentLookupKey(_map);
		}else{
			
			for (ConcurrentHashMap<String, String> map : list) {
				if(map.containsKey(devCode)){
					// 并且设置当前数据为第一个
					determineCurrentLookupKey(map);;
					break;
				}else{
					ConcurrentHashMap<String, String> _map = new ConcurrentHashMap<String, String>();
					_map.put(devCode, cityCode);
					_map.put("devCode", devCode);
					_map.put("cityCode", cityCode);
					list.add(_map);
					// 并且设置当前数据为第一个
					determineCurrentLookupKey(_map);
					break;
				}
			}
		}
	}
	
	/**
	 * 设置当前设备信息为第一个
	 * @param map
	 */
	private static void determineCurrentLookupKey(ConcurrentHashMap<String, String> map){
		dataHolder.get().offerFirst(map);
	}
	
	/**
	 * 设备在当前线程缓存信息(城市编码)
	 * @param devCode
	 * @return
	 */
	public static String getCityCode(){
		return dataHolder.get().getFirst().get("cityCode");
	}
	/**
	 * 设备在当前线程缓存信息(城市编码)
	 * @param devCode
	 * @return
	 */
	public static String getCityCode(String devCode){
		LinkedList<ConcurrentHashMap<String, String>> list = dataHolder.get();
		for (ConcurrentHashMap<String, String> map : list) {
			if(map.contains(devCode)){
				return map.get("cityCode"); 
			}
		}
		return null;
	}
	
	/**
	 * 移除设备在当前线程缓存信息
	 * @param devCode
	 */
	public static void removeDevCode(String devCode){
		LinkedList<ConcurrentHashMap<String, String>> list = dataHolder.get();
		ConcurrentHashMap<String, String> dmap = null;
		for (ConcurrentHashMap<String, String> map : list) {
			if(map.contains(devCode)){
				dmap = map;
				break;
			}
		}
		list.remove(dmap);
	}
}
